<template>
  <!-- 仓库 -->
  <pageTabelLayout>
    <template #pageHeader>
      <div class="my-header">
        <div class="search-form isheader" v-if="headerShow">
          <div>
            <a-form size="mini" :model="queryData1" layout="inline">
              <a-form-item label="所属公司">
                <!-- <a-cascader v-model="queryData1.firmId" :options="gsDatas" allow-clear class="bacClass"
                    @click="getAllActiveCompany"  /> -->
                <a-cascader
                  :options="pageData.corporateList"
                  v-model="queryData1.firmId"
                  allow-clear
                  class="bacClass"
                  :loading="pageData.corporateLoading"
                  @change="queryClearChange"
                  :style="{ width: '160px' }"
                  popup-container="html"
                />
              </a-form-item>
              <a-form-item label="仓库名称">
                <a-select popup-container="html" 
                  class="bacClass"
                  :style="{ width: '160px' }"
                  :loading="loading"
                  :filter-option="false"
                  allow-search
                  allow-clear
                  v-model.trim="queryData1.warehouseName"
                  @click="handleSearchs"
                >
                  <a-option v-for="item in pageData.warehouseName" :value="item.warehouseName">{{
                    item.warehouseName
                  }}</a-option>
                </a-select>
              </a-form-item>

              <!-- <a-form-item label="所属公司" field="firm">
                <a-cascader :options="pageData.corporateList" v-model="queryData1.firmId" allow-clear
                    class="bacClass" :loading="pageData.corporateLoading" />
              </a-form-item>
              <a-form-item label="仓库编号">
                              <a-select popup-container="html"  class="bacClass" :style="{ width: '160px' }" :loading="loading1"
                                        @search="handleSearch1" :filter-option="false" allow-search
                                        v-model.trim="queryData1.warehouseCode" @click="handleSearch1s" allow-clear>
                                  <a-option v-for="item in pageData.warehouseCode" :value="item.warehouseCode">{{
                                      item.warehouseCode
                                      }}
                                  </a-option>
                              </a-select>
                          </a-form-item>
              <a-form-item label="仓库名称">
                <a-select popup-container="html"  class="bacClass" :style="{ width: '160px' }" :loading="loading" :filter-option="false"
                  allow-search v-model.trim="queryData1.warehouseName" @click="handleSearchs" allow-clear>
                  <a-option v-for="item in pageData.warehouseName" :value="item.warehouseName">{{ item.warehouseName }}
                  </a-option>
                </a-select>
              </a-form-item> -->
            </a-form>
          </div>
          <div class="my-tool-bar">
            <Toolbar
              :items="[
                `${permissionStore.hasPermisson('shgl.cx') ? '查询' : ''}`,
                `${permissionStore.hasPermisson('shgl.xz') ? '新增' : ''}`,
                `${permissionStore.hasPermisson('shgl.sc') ? '删除' : ''}`,
              ]"
              @add="addHandler"
              @del="deleteHandler"
              @select="selectHandler"
              @export="exports"
              @cshck="cshck"
            >
            </Toolbar>
          </div>
        </div>
        <div class="my-divisders">
          <a-divider orientation="center">
            <icon-double-up
              v-if="headerShow"
              @click="headerShow = false"
              :strokeWidth="2"
              :size="18"
            />
            <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
          </a-divider>
        </div>
        <!-- <div class="my-tool-bar">
                      <Toolbar :items="['查询', '新增', '删除',]" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                          @export="exports" @cshck="cshck">
                      </Toolbar>
                  </div> -->
      </div>

    <div class="gang"></div>
  </template>
  <template #pageTabel>
    <a-spin :loading="pageData.pageLoading" style="width: 100%; height: 100%">
      <!-- <a-table :style="{ height: '100%' }" size="mini" @page-change="pagination.change" stripe :bordered="true"
                  :columns="tableColumns" :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                  v-model:selected-keys="selectedRowKeys" :loading="table.tableLoading" :data="table.dataList"
                  :pagination="pagination" :rowKey="rowKey">
                  <template #edit="{ record }">
                      <a-space>
                          <a-button type="primary" size="small" status="warning" @click="editHandler(record)">
                              <template #icon>
                                  <icon-edit />
                              </template>
                              修 改
                          </a-button> -->
      <!-- <a-button type="primary" @click="editHandler1(record)">储位</a-button> -->
      <!-- <a-button status="success" @click="openQRcode(record)">查看二维码</a-button>
                      </a-space>
                  </template>
              </a-table> -->
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        :localeText="localeText1"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: calc(100% - 45px);"
        @columnResized="onColumnResized"
        @columnMoved="onColumnMoved"
        @columnVisible="onColumnVisible"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="table.dataList"
        :columnDefs="tc"
      >
      </AgGridVuesCopys>
      <paginationCopys
        :page-size-options="pagingList1"
        :page-size="size"
        :current="page"
        :total="total"
        show-total
        show-jumper
        show-page-size
        @change="PageSize"
        @page-size-change="change1"
        style="justify-content: center"
      />
   
  </a-spin>
</template>
  <a-drawer
    ok-text="保存"
    cancel-text="关闭"
    :drawer-style="{ zIndex: 9999 }"
    :mask-closable="false"
    :width="400"
    :visible="pageData.showAdd"
    unmountOnClose
    @ok="sideOk"
    @cancel="sideNo"
  >
    <template #title>
      {{ pageData.sideTitle }}
    </template>
    <div>
      <!-- 所属工厂 仓库名称 联系人 联系电话 地址 -->
      <a-form ref="formRef" :model="dataForm" layout="horizontal">
        <a-form-item
          label="所属公司"
          field="firmId"
          :rules="[{ required: true, message: '公司必填' }]"
          label-col-flex="80px"
        >
          <a-cascader
            :disabled="pageData.sideTitle == '修改仓库审核'"
            :options="pageData.corporateList"
            @change="corporateChange"
            v-model="dataForm.firmId"
            allow-clear
            class="bacClass"
            ref="corporateRef"
            :loading="pageData.corporateLoading"
            popup-container="html"
          />
        </a-form-item>
        <a-form-item
          label="仓库名称"
          field="tg"
          :rules="[{ required: true, message: '名称必填' }]"
          label-col-flex="80px"
        >
          <a-select popup-container="html" 
            v-if="pageData.sideTitle != '修改仓库审核'"
            class="bacClass"
            :loading="loading"
            :filter-option="false"
            allow-search
            v-model="dataForm.tg"
            @click="handleSearchs2('')"
            @search="handleSearchs2($event)"
            allow-clear
          >
            <a-option v-for="item in pageData.warehouseName" :value="item.id"
              >{{ item.warehouseName }}
            </a-option>
          </a-select>
          <a-select popup-container="html" 
            v-else
            disabled
            class="bacClass"
            :loading="loading"
            :filter-option="false"
            allow-search
            v-model="dataForm.tg"
            @click="handleSearchs2"
            allow-clear
          >
            <a-option v-for="item in pageData.warehouseName" :value="item.id"
              >{{ item.warehouseName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="单据类型"
          field="warehouseCode"
          :rules="[{ required: true, message: '类型必填' }]"
          label-col-flex="80px"
        >
          <a-select popup-container="html" 
            class="bacClass"
            :disabled="pageData.sideTitle == '修改仓库审核'"
            allow-search
            v-model="dataForm.warehouseCode"
            allow-clear
          >
            <a-option :value="0">入库单</a-option>
            <a-option :value="1">出库单</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="审核状态"
          field="pricingWay"
          :rules="[{ required: true, message: '状态必填' }]"
          label-col-flex="80px"
        >
          <a-select popup-container="html"  class="bacClass" allow-search v-model="dataForm.pricingWay" allow-clear>
            <a-option :value="0">需要审核</a-option>
            <a-option :value="1">无需审核</a-option>
          </a-select>
        </a-form-item>
        <!-- <a-form-item label="编号" field="warehouseCode"
                      :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]" label-col-flex="80px">
                      <a-input placeholder="请输入编号" @blur="inputBlur" v-model.trim="dataForm.warehouseCode" />
                  </a-form-item> -->
        <!-- <a-form-item label="仓库名称" field="warehouseName" :rules="[{ required: true, message: '仓库名称必填' }]"
                      :validate-trigger="['change', 'blur']" label-col-flex="80px">
                      <a-input placeholder="请输入仓库名称" v-model.trim="dataForm.warehouseName" />
                  </a-form-item> -->
        <!-- <a-form-item label="计价方式" field="pricingWay" :rules="[{ required: true, message: '计价方式必填' }]"
                      label-col-flex="80px">
                      <a-select popup-container="html"  class="bacClass" v-model.trim="dataForm.pricingWay" @click="jjFdsFun">
                          <a-option v-for="item in jjFds">{{ item.detailName }}</a-option>
                      </a-select>
                  </a-form-item> -->
        <!-- <a-form-item label="自定义代号" field="extendCode">
                      <a-input placeholder="请输入自定义代号" v-model="dataForm.extendCode" />
                  </a-form-item> -->
        <a-form-item label="备注" field="remark" label-col-flex="80px">
          <a-textarea
            class="bacClass"
            v-model="dataForm.remark"
            :max-length="400"
            allow-clear
            show-word-limit
          />
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
  <ModalDialog :mask-closable="false" ref="qrModal" title="仓库二维码" @confirm="gbModal">
    <template #content>
      <a-space direction="vertical">
        <a-button type="primary" @click="print">打印</a-button>
        <div id="auditmanage" style="width: 400px">
          <QrcodeVue :value="qrData.code"></QrcodeVue>
          <div style="display: inline-block; vertical-align: top; margin-left: 15px">
            <div style="width: 200px">公司 {{ qrData.gcName }}</div>
            <div style="width: 200px">仓库编号 {{ qrData.ckCode }}</div>
            <div style="width: 200px">仓库类型 {{ qrData.ckType }}</div>
            <div style="width: 200px">仓库名称 {{ qrData.ckName }}</div>
            <div style="width: 200px">计价方式 {{ qrData.jsjia }}</div>
          </div>
        </div>
      </a-space>
    </template>
  </ModalDialog>
</pageTabelLayout>
</template>

<script lang="ts">
  import axios from 'axios'
  import { get, post } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import QrcodeVue from 'qrcode.vue'
  import printJS from 'print-js'
  import { ModalDialogType } from '@/types/components'
  import { ref, reactive, onMounted, toRefs, defineComponent } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import ModalDialog from '@/components/ModalDialog.vue'
  
  import { localeText } from '@/api/aggridZw'
  import usePermission from '@/store/modules/permission'
  import { pagingList } from '@/api/paging'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import { slicing } from '@/utils/caseFrimAndSecRig'
  interface Firm {
    name: string
    id: number
  }

  interface Cloth {
    code: string
  }

  interface WarehouserSrttingsInfo {
    id: any
    firm: any
    warehouseCode: any
    warehouseName: any
    pricingWay: any
    remark: any
    deleteState: any
    createName: any
    createTime: any
    updateName: any
    updateTime: any
    obsoleteState: any
    warehouseTypeName: any
    extendCode: any
    warehouseTypeId: any
    tg: any
    firmName: any
    firmId: Number
    tgId: any
  }

  interface dataListType {
    shelveName: any
    shelveCode: any
    storageName: any
    storageCode: any
  }

  export default {
    name: 'WarehouseSettings',
    setup() {
      const permissionStore: any = usePermission()
      const total = ref(10)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: 'wms/auditSet/getPage',
          data: {
            page: page.value,
            size: size.value,
            warehouse: queryData1.warehouseName,
            // warehouseName:queryData1.warehouseName,
            firmId: queryData1.firmId,
            deleteState: '0',
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              gridOption.value.setRowData(data.list)
              pagination.setTotalSize(data.total)
              total.value = data.total
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const table1 = useTable()
      const rowKey = useRowKey('id')
      //假数据后期需要修改
      // const dataList = reactive({
      //     list:[{
      //         id:1,
      //         code:1,
      //         mercery_name:'掌紫元',
      //         remark:"WH22101800000002",
      //         remark_1:'裁断中仓',
      //         remark_2:'佛山',
      //         remark_3:'勇哥',
      //         remark_4:'110'
      //     }]
      // })
      let qrModal = ref<ModalDialogType | null>(null)
      const qrData = reactive({
        ckName: '',
        gcName: '',
        code: '',
        ckCode: '',
        ckType: '',
        jsjia: '',
      })
      const openQRcode = (item: any) => {
        console.log(item)
        qrData.gcName = item.firm
        qrData.ckName = item.warehouseName
        qrData.ckCode = item.warehouseCode
        qrData.ckType = item.warehouseTypeName
        qrData.jsjia = item.pricingWay
        qrData.code = JSON.stringify({
          id: item.id,
          firmId: item.firmId,
          warehouseCode: item.warehouseCode,
          warehouseTypeId: item.warehouseTypeId,
        })
        qrModal.value?.toggle()
      }
      // 序号	所属工厂	仓库编码	仓库名称	仓库地址	联系人	联系电话	操作
      const tableColumns = useTableColumn([
        {
          title: '公司',
          key: 'firm',
          dataIndex: 'firm',
          width: 150,
        },
        {
          title: '仓库名称',
          key: 'warehouse',
          dataIndex: 'warehouse',
          width: 150,
        },
        {
          title: '单据类型',
          key: 'infoType',
          dataIndex: 'infoType',
          slotName: 'infoType',
          width: 150,
        },
        {
          title: '审核状态',
          key: 'auditState',
          dataIndex: 'auditState',
          slotName: 'auditState',
          width: 150,
        },
        {
          title: '备注',
          key: 'remark',
          dataIndex: 'remark',
          width: 150,
        },
        {
          title: '操作',
          key: 'edit',
          dataIndex: 'edit',
          slotName: 'edit',
          width: 150,
          fixed: 'right',
        },
      ])
      const columns = [
        {
          title: '布笼名称',
          dataIndex: 'shelveName',
          slotName: 'shelveName',
        },
        {
          title: '布笼自定义代号',
          dataIndex: 'shelveCode',
          slotName: 'shelveCode',
        },
        {
          title: '储位名称',
          dataIndex: 'storageName',
          slotName: 'storageName',
        },
        {
          title: '储位自定义代号',
          dataIndex: 'storageCode',
          slotName: 'storageCode',
        },
        {
          title: '操作',
          dataIndex: 'save',
          slotName: 'save',
        },
      ]
      const dataLists = ref<dataListType[]>([
        {
          shelveName: '',
          shelveCode: '',
          storageName: '',
          storageCode: '',
        },
      ])
      const pageData: any = reactive({
        gcList: [],
        clothList: [],
        showAdd: false,
        sideTitle: '新增布料基础资料',
        rHeight: 0,
        warehouseName: [],
        warehouseCode: [],
        pageLoading: false,
        corporateList: [],
        corporateLoading: false,
      })
      // const pageData1 = reactive<{
      //     showAdd: boolean;
      // }>({
      //     showAdd: false,
      // });
      let jjFds = ref<any[]>([])
      const jjFdsFun = () => {
        post({
          url: 'dict/dictTypeDetail/getList',
          data: {
            codeType: 1,
            obsoleteState: 0,
            deleteState: 0,
          },
        }).then((res: any) => {
          if (res.code === 200) {
            jjFds.value = res.data
          } else {
            Message.error(res.message)
          }
        })
      }
      const corporateRef = ref<any>()
      const corporateChange = (event: any) => {
        const firm = pageData.corporateList.find((item: any) => item.value === event)['label']
        dataForm.firm = firm
        // dataForm.firm = nextTick(() => {
        //   dataForm.firm = slicing(corporateRef.value.selectViewValue[0].label)
        // })
      }
      // 获取公司列表
      const getCorporateList = async () => {
        try {
          pageData.corporateLoading = true
          const res = await post({ url: 'org/baCompany/getTreeCompanyByUser' })
          if (res.code == 200) {
            pageData.corporateList = res.data
            return
          }
          Message.error(res.message)
        } catch (error: any) {
          pageData.corporateLoading = false
        } finally {
          pageData.corporateLoading = false
        }
      }
      onMounted(() => {
        doRefresh()
        getCorporateList()
        pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
        //弹出层的高
        if (pageData.rHeight !== undefined) {
          pageData.rHeight = pageData.rHeight - 100
        }
      })
      const queryData = reactive({
        firm: '',
        clothType: '',
      })
      const queryData1 = reactive({
        warehouseName: '',
        warehouseCode: '',
        firm: '',
        firmId: undefined,
      })
      const cklxTable = ref<any[]>([])
      const addHandler = () => {
        ;(queryData1.warehouseCode = ''),
          (queryData1.warehouseName = ''),
          post({
            url: 'wms/warehouseType/getWarehoursTypePara',
            data: {
              obsoleteState: 0,
            },
          }).then(({ data, code }: any) => {
            if (code === 200) {
              cklxTable.value = data
            }
          })
        pageData.showAdd = true
        pageData.sideTitle = '新增仓库审核'
        for (let item in dataForm) {
          dataForm[item] = ''
        }
      }
      // onMounted(() => {
      //   pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
      //   //弹出层的高
      //   if (pageData.rHeight !== undefined) {
      //     pageData.rHeight = pageData.rHeight
      //   }
      // })
      let gsDatas = ref<any[]>([])
      // 获取公司下拉框
      // const getAllActiveCompany = () => {
      //   post({
      //     url: 'org/firmGroup/getFirmInfoByMap',
      //     data: {},
      //   }).then((res) => {
      //     if (res.code == 200) {
      //       gsDatas.value = res.data
      //     }
      //   })
      // }
      const queryClearChange = () => {
        pageData.warehouseName = []
        queryData1.warehouseName = ''
      }

      const getAllActiveCompanys = (val: any) => {
        const frimNameList: any = gsDatas2.value.filter((item: any) => {
          return item.id == val
        })
        dataForm.firmId = frimNameList[0].id
        dataForm.firmName =
          frimNameList[0].typeName == ''
            ? frimNameList[0].firmName
            : frimNameList[0].typeName + '-' + frimNameList[0].firmName
      }

      const dataForm = reactive<WarehouserSrttingsInfo>({
        id: '',
        firm: '',
        warehouseCode: '',
        warehouseName: '',
        pricingWay: '',
        remark: '',
        deleteState: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        obsoleteState: '',
        warehouseTypeName: '',
        extendCode: '',
        warehouseTypeId: '',
        tg: '',
        firmName: '',
        firmId: 0,
        tgId: '',
      })
      const formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            if (pageData.sideTitle == '新增仓库审核') {
              gsDatas2.value.forEach((o: any) => {
                if (o.id == dataForm.firm) {
                  dataForm.firmId = o.typeName == '' ? o.firmName : o.typeName + '-' + o.firmName
                }
              })
              pageData.warehouseName.forEach((o: any) => {
                if (o.id == dataForm.tg) {
                  dataForm.tgId = o.warehouseName
                }
              })
              post({
                url: 'wms/auditSet/insert',
                data: [
                  {
                    firm: dataForm.firm,
                    firmId: dataForm.firmId,
                    warehouse: dataForm.tgId,
                    warehouseId: dataForm.tg,
                    infoType: dataForm.warehouseCode,
                    auditState: dataForm.pricingWay,
                    remark: dataForm.remark,
                  },
                ],
              }).then((res: any) => {
                if (res.code === 200) {
                  for (let i in dataForm) {
                    dataForm[i] = ''
                  }
                  formRef.value?.resetFields()
                  doRefresh()
                  pageData.showAdd = false
                  Message.success({
                    content: '添加成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            } else if (pageData.sideTitle == '修改仓库审核') {
              gsDatas2.value.forEach((o: any) => {
                if (o.id == dataForm.firm) {
                  dataForm.firmId = o.typeName == '' ? o.firmName : o.typeName + '-' + o.firmName
                }
              })
              pageData.warehouseName.forEach((o: any) => {
                if (o.id == dataForm.tg) {
                  dataForm.tgId = o.warehouseName
                }
              })
              post({
                url: 'wms/auditSet/update',
                data: [
                  {
                    id: dataForm.id,
                    firm: dataForm.firm,
                    firmId: dataForm.firmId,
                    warehouse: dataForm.tgId,
                    warehouseId: dataForm.tg,
                    infoType: dataForm.warehouseCode,
                    auditState: dataForm.pricingWay,
                    remark: dataForm.remark,
                  },
                ],
              }).then((res: any) => {
                if (res.code === 200) {
                  for (let i in dataForm) {
                    dataForm[i] = ''
                  }
                  formRef.value?.resetFields()
                  doRefresh()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
            }
          }
        })
      }

      const sideNo = () => {
        pageData.showAdd = false
      }
      // const sideNo1 = () => {
      //     pageData1.showAdd = false
      // }
      var id = ''
      const editHandler = (key: any) => {
        dataForm.firm = key.firm
        dataForm.firmId = key.firmId
        dataForm.tg = Number(key.warehouseId)
        dataForm.tgId = key.warehouse
        dataForm.warehouseCode = key.infoType
        dataForm.pricingWay = Number(key.auditState)
        dataForm.remark = key.remark
        dataForm.id = key.id
        pageData.showAdd = true
        pageData.sideTitle = '修改仓库审核'
        id = key.id
        // post({
        //   url: 'org/firmGroup/getFirmInfoByMap',
        //   data: {},
        // }).then((res) => {
        //   if (res.code == 200) {
        //     gsDatas2.value = res.data
        //   }
        // })
        post({
          url: 'wms/warehouse/getWarehouseByPara',
          data: {
            firmId: dataForm.firmId,
            virtuallyState: 0,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            pageData.warehouseName = res.data
          } else {
            Message.error(res.message)
          }
        })
      }
      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          return
        }

        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            post({
              url: 'wms/auditSet/delete',
              data: gridOption.value.getSelectedRows().map((item: any) => {
                return item.id
              }),
            }).then(({ code, data }: any) => {
              if (code === 200) {
                doRefresh()
                pageData.showAdd = false
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 5000,
                })
              }
            })
          },
        })
      }
      const print = () => {
        printJS({
          printable: 'auditmanage',
          type: 'html',
          targetStyles: ['*'],
        })
      }
      const gbModal = () => {
        qrModal.value?.toggle()
      }
      const selectHandler = () => {
        page.value = 1
        doRefresh()
      }
      const visible = ref(false)
      const handleOk = () => {
        visible.value = !visible.value
      }
      const handleCancel = () => {
        visible.value = !visible.value
      }
      let keyList = {
        keyFrim: '',
        keyId: 0,
      }
      // const editHandler1 = (key: any) => {
      //     keyList.keyFrim = key.firm
      //     keyList.keyId = key.id
      //     opCwdata(key)
      //     pageData1.showAdd = true
      // }
      // function opCwdata(key:any){
      //     post({
      //         url: "wms/warehouse/getShelveStoragetPara",
      //         data: {
      //             firm: key.firm,
      //             warehouseId: Number(key.id)
      //         },
      //     })
      //         .then(({ data, status }: any) => {
      //             if (status === 200) {
      //                 dataLists.value = data
      //                 // dataLists.value.forEach((item,index)=>{
      //                 //     item.key = index+1
      //                 // })
      //                 // console.log(dataLists.value)
      //             }
      //         })
      //         .catch(console.log);
      // }
      const addHandler1 = () => {
        dataLists.value.push({
          shelveName: '',
          shelveCode: '',
          storageName: '',
          storageCode: '',
        })
      }
      const bcCw = (key: any) => {
        let infoLists = {
          shelveName: key.shelveName,
          storgeName: key.storageName,
          shelveId: null,
        }
        console.log(infoLists)
        post({
          url: 'wms/warehouse/addShelveStorage',
          data: {
            firm: keyList.keyFrim,
            warehouseId: Number(keyList.keyId),
            infoList: [infoLists],
          },
        })
          .then(({ data, code, message }: any) => {
            if (code === 200) {
              Message.success('新增成功')
            } else {
              Message.error(message)
            }
          })
          .catch(console.log)
      }
      const options = ref<any>(pageData.warehouseName)
      const options1 = ref<any>(pageData.warehouseCode)
      const loading = ref(false)
      const loading1 = ref(false)
      // const handleSearch = (value: any) => {
      //     if (value) {
      //         const ob = {warehouseName: value}
      //         loading.value = true;
      //         window.setTimeout(() => {
      //             selCxAll(ob);
      //             options.value = pageData.warehouseName;
      //             loading.value = false;
      //         }, 100)
      //     } else {
      //         options.value = []
      //     }
      // };
      const handleSearch1 = (value: any) => {
        if (value) {
          const ob = { warehouseCode: value }
          loading1.value = true
          window.setTimeout(() => {
            selCxAll1(ob)
            options1.value = pageData.warehouseCode
            loading1.value = false
          }, 100)
        } else {
          options.value = []
        }
      }

      function selCxAll(val: any) {
        post({
          url: 'wms/warehouse/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            console.log(data)
            pageData.warehouseName = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      function selCxAll1(val: any) {
        post({
          url: 'wms/warehouse/getFieldValue',
          data: val,
        }).then(({ data, code }: any) => {
          if (code === 200) {
            console.log(data)
            pageData.warehouseCode = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const handleSearch1s = () => {
        post({
          url: 'wms/warehouse/getFieldValue',
          data: {
            warehouseCode: '',
          },
        }).then(({ data, code }: any) => {
          if (code === 200) {
            console.log(data)
            pageData.warehouseCode = data
          } else {
            Message.error({
              content: '查询失败！',
              duration: 5000,
            })
          }
        })
      }

      const handleSearchs = () => {
        if (queryData1.firmId == undefined || queryData1.firmId == '') {
          pageData.warehouseName = []
          Message.warning('请先选择公司')
          return
        }
        post({
          url: 'wms/warehouse/getWarehouseByPara',
          data: {
            firmId: queryData1.firmId,
            virtuallyState: 0,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            pageData.warehouseName = res.data
          } else {
            Message.error(res.message)
          }
        })
      }
      const handleSearchs2 = (val: any) => {
        if (dataForm.firmId == '') {
          pageData.warehouseName = []
          Message.error('请先选择公司')
          return
        }
        const resData: any = gsDatas2.value.filter((item: any) => {
          return item.id == dataForm.firm
        })
        post({
          url: 'wms/warehouse/getFieldValue2',
          data: {
            firmId: dataForm.firmId,
            warehouseName: val,
            deleteState: 0,
          },
        }).then((res: any) => {
          if (res.code == 200) {
            pageData.warehouseName = res.data
          } else {
            Message.error(res.message)
          }
        })
      }
      const exports = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error('请先勾选')
          return
        } else {
          //将表头拼接出来
          let head =
            '<th>仓库编号</th><th>仓库类型</th><th>仓库名称</th><th>计件方式</th><th>备注</th>'
          //拿到当前表格数据与勾选的行做筛选

          let nowRow = table.dataList.filter(function (o) {
            return (
              gridOption.value
                .getSelectedRows()
                .map((o: any) => {
                  return o.id
                })
                .indexOf(o['id']) !== -1
            )
          })
          let body = ''
          nowRow.forEach(function (o) {
            body += '<tr><td>' + o['warehouseCode'] + '</td>'
            body += '<td>' + o['warehouseTypeName'] + '</td>'
            body += '<td>' + o['warehouseName'] + '</td>'
            body += `<td>${o['pricingWay']}</td>`
            body += `<td>${o['remark']}</td>`
            body += '</tr>'
          })
          tableToXlsx(head, '仓库', body)
          console.log(table)
        }
      }

      function tableToXlsx(head: any, filename: any, body: any) {
        const uri = 'data:application/vnd.ms-excel;base64,',
          template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

        const a = document.createElement('a')
        a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
        a.download = filename
        a.click()
        document.removeChild(a)
      }

      const isChiese = (value: string, cb: Function) => {
        return new Promise<void>((resolve) => {
          if (window.encodeURI(value).indexOf('%') !== -1) {
            cb('填写的值不能包含中文！')
          }
          resolve()
        })
      }
      const headerShow = ref<boolean>(true)
      //初始化仓库
      const cshck = () => {
        pageData.pageLoading = true
        get({
          url: 'wms/warehouse/initWareHouseByFirm',
        })
          .then((res: any) => {})
          .finally(() => {
            pageData.pageLoading = false
          })
      }
      const gsDatas2 = ref<any[]>([])
      // const getAllActiveCompany2 = () => {
      //   post({
      //     url: 'org/firmGroup/getFirmInfoByMap',
      //     data: {},
      //   }).then((res) => {
      //     if (res.code == 200) {
      //       gsDatas2.value = res.data
      //     }
      //   })
      // }
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        flex: 1,
      }
      let tc: any[] = tableColumns.map((o: any) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
        }
        if (o.slotName === 'edit') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 140
          obj['cellRenderer'] = {
            template: `<a-space>
                        <a-button v-if="e" style="position:relative;left:10px" type="primary" size="small" status="warning" @click="a1">
                            <template #icon>
                                <icon-edit />
                            </template>
                            修 改
                        </a-button>
                            </a-space>
                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              const a1 = () => {
                editHandler(props.params.data)
              }
              return {
                a1,
                isDtas,
                e: permissionStore.hasPermisson('shgl.xg'),
              }
            },
          }
        }
        if (o.slotName === 'infoType') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 210
          obj['cellRenderer'] = {
            template: `
                    <span v-if='isDtas.infoType == 0'>入库单</span>
                    <span v-if='isDtas.infoType == 1'>出库单</span>
                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              return {
                isDtas,
              }
            },
          }
          obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0'
          ? '入库单'
          : params.value == '1'
          ? '出库单'
          : ''
      },
    }
        }
        if (o.slotName === 'auditState') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 210
          obj['cellRenderer'] = {
            template: `
                    <span v-if='isDtas.auditState == 0'>需要审核</span>
                    <span v-if='isDtas.auditState == 1'>无需审核</span>
                    `,
            setup(props: any) {
              const isDtas = ref(props.params.data)
              return {
                isDtas,
              }
            },
          }
          obj['filterParams'] = {
      valueFormatter: function (params: any) {
        return params.value == '0'
          ? '需要审核'
          : params.value == '1'
          ? '无需审核'
          : ''
      },
    }
          
        }
        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      const localeText1: any = ref(localeText)
      const pagingList1: any = ref(pagingList)
      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('AuditManagement-1', gridOption, colState, tc)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      return {
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        pagingList1,
        localeText1,
        handleSearchs2,
        change1,
        PageSize,
        total,
        page,
        size,
        tc,
        defaultColDef,
        gridReady,
        gridOption,
        // getAllActiveCompany2,
        gsDatas2,
        cshck,
        jjFdsFun,
        headerShow,
        isChiese,
        handleSearchs,
        handleSearch1s,
        jjFds,
        exports,
        bcCw,
        addHandler1,
        dataLists,
        columns,
        // sideOk1,
        // sideNo1,
        // pageData1,
        table1,
        // editHandler1,
        handleCancel,
        handleOk,
        visible,
        selectHandler,
        cklxTable,
        gbModal,
        print,
        editHandler,
        sideNo,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        getCorporateList,
        corporateChange,
        corporateRef,
        qrModal,
        qrData,
        openQRcode,
        queryData1,
        loading,
        loading1,
        // handleSearch,
        handleSearch1,
        gsDatas,
        // getAllActiveCompany,
        queryClearChange,
        getAllActiveCompanys,
        permissionStore,
      }
    },
    components: { Toolbar, QrcodeVue, ModalDialog,  },
  }
</script>
<style scoped lang="less">
  .cwTitle {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .selectCc {
    width: 100%;
    text-align: right;
    margin-right: 20px;
    margin-bottom: 10px;
  }

  .selectCc {
    width: 100%;
    text-align: right;
    margin-right: 20px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }
</style>
